// package input 命令行的用户输入
package input

import (
	"fmt"
	"net"
	"strconv"
	"strings"

	"gitee.com/sillyman/simpleUtil/network/macaddr"
)

// String 提示用户输入，然后返回用户输入的值。
// 参数：
//		prompt 用户输入前的提示
// 		defaultVal 默认的值，如果用户直接回车则返回默认值
// 		checkFn 检查函数，如果返回false，则继续提示用户输入
func String(prompt string, defaultVal string, checkFn func(v string) bool) string {
	for {
		var s string
		fmt.Printf("%s(%s): ", prompt, defaultVal)
		fmt.Scanln(&s)
		s = strings.TrimSpace(s)
		if s == "" {
			return defaultVal
		}

		if checkFn != nil && checkFn(s) {
			return s
		}
	}
}

func Int(prompt string, defaultVal int64, checkFn func(v int64) bool) int64 {
	for {
		var s string
		fmt.Printf("%s(%d): ", prompt, defaultVal)
		fmt.Scanln(&s)
		s = strings.TrimSpace(s)
		if s == "" {
			return defaultVal
		}

		i64, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			continue
		}

		if checkFn != nil && checkFn(i64) {
			return i64
		}
	}
}

func Float64(prompt string, defaultVal float64, checkFn func(v float64) bool) float64 {
	for {
		var s string
		fmt.Printf("%s(%f): ", prompt, defaultVal)
		fmt.Scanln(&s)
		s = strings.TrimSpace(s)
		if s == "" {
			return defaultVal
		}

		f, err := strconv.ParseFloat(s, 64)
		if err != nil {
			continue
		}

		if checkFn != nil && checkFn(f) {
			return f
		}
	}
}

func IP(prompt string, defaultValue net.IP, checkFn func(v net.IP) bool) net.IP {
	for {
		var s string
		fmt.Printf("%s(%s): ", prompt, defaultValue)

		fmt.Scanln(&s)
		s = strings.TrimSpace(s)
		if s == "" {
			return defaultValue
		}

		ip := net.ParseIP(s)
		if ip == nil {
			continue
		}

		if checkFn != nil && checkFn(ip) {
			return ip
		}
	}
}

func MAC(prompt string, defaultValue macaddr.MAC, checkFn func(v macaddr.MAC) bool) macaddr.MAC {
	for {
		var s string
		fmt.Printf("%s(%s): ", prompt, defaultValue)

		fmt.Scanln(&s)
		s = strings.TrimSpace(s)
		if s == "" {
			return defaultValue
		}

		mac := macaddr.Parse(s)
		if mac != nil {
			continue
		}

		if checkFn != nil && checkFn(mac) {
			return mac
		}
	}
}
